﻿using System.Drawing;
using System.Drawing.Imaging;
using ZXing;
using ZXing.Common;
using ZXing.Rendering;

namespace AMS.Common.ToolChains.Barcode;

public class BarcodeGenerator
{
    public static void Generate()
    {
        var writer = new BarcodeWriterPixelData()
        {
            Format = BarcodeFormat.CODE_39
        };

        var opts = new EncodingOptions
        {
            Width = 512,
            Height = 128,
            Margin = 2
        };

        writer.Options = opts;

        var pixelData = writer.Write("Hello");

        var bmp = PixelToBitmap(pixelData);

        bmp.Save(Path.Combine(AppContext.BaseDirectory, "barcode.bmp"));
    }

    private static Bitmap PixelToBitmap(PixelData pixelData)
    {
        var bmp = new Bitmap(pixelData.Width, pixelData.Height, PixelFormat.Format32bppArgb);
        var bmpData = bmp.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

        var iptr = bmpData.Scan0;

        System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, iptr, pixelData.Pixels.Length);
        bmp.UnlockBits(bmpData);

        return bmp;
    }
}